package com.souku.finance.application.utils;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.WriterException;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.QRCodeWriter;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.nostra13.universalimageloader.core.assist.ImageScaleType;
import com.nostra13.universalimageloader.core.download.BaseImageDownloader;
import com.souku.finance.application.R;

import java.io.BufferedOutputStream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Hashtable;
import java.util.List;

/**
 * Created by Administrator on 2016/5/30.
 */
public class UploadImageUtil {

    public static final int REQUEST_FIX = 1;
    public static final int REQUEST_IMAGE = 2;
    public static final int REQUEST_PHOTO = 3;

    public static void startPhotoZoom(Activity context, Uri uri, File pictureFile) {
        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.setDataAndType(uri, "image/*");
        //下面这个crop=true是设置在开启的Intent中设置显示的VIEW可裁剪
        intent.putExtra("crop", "true");// 剪切图片
        // aspectX aspectY 是宽高的比例
        intent.putExtra("aspectX", 1);
        intent.putExtra("aspectY", 1);
        // outputX outputY 是裁剪图片宽高
        intent.putExtra("outputX", 450);// 输出的图片宽
        intent.putExtra("outputY", 450);// 输出的图片高
        intent.putExtra("output", Uri.fromFile(pictureFile)); // 输出的图片路径
//        intent.putExtra("return-data", true);
        intent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString()); // 输出的图片格式
        intent.setAction(Intent.ACTION_GET_CONTENT);
        context.startActivityForResult(intent, REQUEST_FIX);
    }

    public static Bitmap setPicToView(Intent picdata) {
        Bundle extras = picdata.getExtras();
        if (extras != null) {
            Bitmap photo = extras.getParcelable("data");
//            Drawable drawable = new BitmapDrawable(photo);
            /**
             * 下面注释的方法是将裁剪之后的图片以Base64Coder的字符方式上
             * 传到服务器，QQ头像上传采用的方法跟这个类似
             */

			/*ByteArrayOutputStream stream = new ByteArrayOutputStream();
            photo.compress(Bitmap.CompressFormat.JPEG, 60, stream);
			byte[] b = stream.toByteArray();
			// 将图片流以字符串形式存储下来

			tp = new String(Base64Coder.encodeLines(b));
			这个地方大家可以写下给服务器上传图片的实现，直接把tp直接上传就可以了，
			服务器处理的方法是服务器那边的事了，吼吼

			如果下载到的服务器的数据还是以Base64Coder的形式的话，可以用以下方式转换
			为我们可以用的图片类型就OK啦...吼吼
			Bitmap dBitmap = BitmapFactory.decodeFile(tp);
			Drawable drawable = new BitmapDrawable(dBitmap);
			*/
            return photo;
        }
        return null;
    }

    public static byte[] Bitmap2Bytes(Bitmap bm) {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        bm.compress(Bitmap.CompressFormat.PNG, 100, baos);
        return baos.toByteArray();
    }


    public static Bitmap Bytes2Bimap(byte[] b) {
        if (b.length != 0) {
            return BitmapFactory.decodeByteArray(b, 0, b.length);
        } else {
            return null;
        }
    }

    public static File saveBitmapFile(Activity context, Bitmap bitmap) {
        String s = context.getCacheDir().getPath() + "/avatar.png";

        File file = new File(s);//将要保存图片的路径
        try {
            BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(file));
            bitmap.compress(Bitmap.CompressFormat.PNG, 100, bos);
            bos.flush();
            bos.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return file;
    }

    public static List<String> getUploadNames(List<String> oldNames) {
        List<String> strings = new ArrayList<String>();
        for (int i = 0; i < oldNames.size(); i++) {
            String[] str = oldNames.get(i).split("\\.");
            String s1 = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
            String s2 = (int) (Math.random() * 9000 + 1000) + "";
            String s3 = str[str.length - 1];
            strings.add(s1.trim() + s2.trim() + i + "." + s3.trim());
        }
        return strings;
    }

    public static String getUploadName(String oldNames) {
        String[] str = oldNames.split("\\.");
        String s1 = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
        String s2 = (int) (Math.random() * 90000 + 10000) + "";
        String s3 = str[str.length - 1];
        oldNames = s1.trim() + s2.trim() + "." + s3.trim();
        return oldNames;
    }

    // 将byte数组转换成InputStream
    public static InputStream byteTOInputStream(byte[] in) {
        ByteArrayInputStream is = new ByteArrayInputStream(in);
        return is;
    }

    private static DisplayImageOptions options = null;

    private static DisplayImageOptions options_1 = null;
    private static ImageLoaderConfiguration config = null;


    /**
     * 设置常用的设置项
     *
     * @return
     */
    public static DisplayImageOptions getSimpleOptions(int imgId) {
        if (options != null) {
            return options;
        }
        options = new DisplayImageOptions.Builder()
                .showImageOnLoading(imgId) // 设置图片在下载期间显示的图片
                .showImageForEmptyUri(imgId)// 设置图片Uri为空或是错误的时候显示的图片
                .showImageOnFail(imgId) // 设置图片加载/解码过程中错误时候显示的图片
                .cacheInMemory(true)// 设置下载的图片是否缓存在内存中
                .cacheOnDisk(true)// 设置下载的图片是否缓存在SD卡中
//                .imageScaleType(ImageScaleType.IN_SAMPLE_INT)// 设置图片以如何的编码方式显示
//                .considerExifParams(true).bitmapConfig(Bitmap.Config.RGB_565)// 设置图片的解码类型
                .imageScaleType(ImageScaleType.EXACTLY)
                .resetViewBeforeLoading(false)
                .build();// 构建完成

        return options;
    }

    /**
     * 设置常用的设置项
     *
     * @return
     */
    public static DisplayImageOptions getSimpleOptions() {
        getSimpleOptions(R.drawable.shipin);
        return options;
    }

    /**
     * 设置常用的设置项
     *
     * @return
     */
    public static DisplayImageOptions getSimpleOptions1() {
        if (options_1 != null) {
            return options_1;
        }
        options_1 = new DisplayImageOptions.Builder()
//				.showImageOnLoading(R.drawable.background) // 设置图片在下载期间显示的图片
//				.showImageForEmptyUri(R.drawable.background)// 设置图片Uri为空或是错误的时候显示的图片
//				.showImageOnFail(R.drawable.background) // 设置图片加载/解码过程中错误时候显示的图片
                .cacheInMemory(true)// 设置下载的图片是否缓存在内存中
                .cacheOnDisk(true)// 设置下载的图片是否缓存在SD卡中
//                .imageScaleType(ImageScaleType.IN_SAMPLE_INT)// 设置图片以如何的编码方式显示
//                .considerExifParams(true).bitmapConfig(Bitmap.Config.ARGB_8888)// 设置图片的解码类型
                .imageScaleType(ImageScaleType.EXACTLY)
                .resetViewBeforeLoading(false)
                .build();// 构建完成
        return options_1;
    }


    public static ImageLoaderConfiguration getImageLoaderConfiguration(Context context) {
        if (config != null) {
            return config;
        }
        config = new ImageLoaderConfiguration.Builder(context).imageDownloader(new BaseImageDownloader(context, 2 * 1000, 10 * 1000)).build();
        return config;
    }

    public static DisplayImageOptions getOptionsMatchView() {

        DisplayImageOptions options = new DisplayImageOptions.Builder()
                .imageScaleType(ImageScaleType.EXACTLY_STRETCHED)
                .cacheInMemory(true)// 设置下载的图片是否缓存在内存中
                .cacheOnDisk(true)// 设置下载的图片是否缓存在SD卡中
                .build();
        return options;
    }


    public static byte[] bmpToByteArray(final Bitmap bmp, final boolean needRecycle) {
        ByteArrayOutputStream output = new ByteArrayOutputStream();
        bmp.compress(Bitmap.CompressFormat.PNG, 100, output);
        if (needRecycle) {
            bmp.recycle();
        }
        byte[] result = output.toByteArray();
        try {
            output.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }


    public static void saveImageToGallery(Context context, Bitmap bmp) {
        // 首先保存图片
        File appDir = new File(Environment.getExternalStorageDirectory(), "Boohee");
        if (!appDir.exists()) {
            appDir.mkdir();
        }
        String fileName = System.currentTimeMillis() + ".jpg";
        File file = new File(appDir, fileName);
        try {
            FileOutputStream fos = new FileOutputStream(file);
            bmp.compress(Bitmap.CompressFormat.JPEG, 100, fos);
            fos.flush();
            fos.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        // 其次把文件插入到系统图库
        try {
            MediaStore.Images.Media.insertImage(context.getContentResolver(),
                    file.getAbsolutePath(), fileName, null);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        // 最后通知图库更新
        context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.parse("file://" + Environment.getExternalStorageDirectory())));
        ToastUtil.show("保存成功");
    }


    /**
     * 生成二维码
     *
     * @param url    二维码链接
     * @param width  生成的图片宽度
     * @param height 高度
     * @return
     */
    public static Bitmap createQRImage(String url, final int width, final int height) {
        try {
            if (url == null || "".equals(url) || url.length() < 1) {
                return null;
            }
            Hashtable<EncodeHintType, String> hints = new Hashtable<EncodeHintType, String>();
            hints.put(EncodeHintType.CHARACTER_SET, "utf-8");
            BitMatrix bitMatrix = new QRCodeWriter().encode(url,
                    BarcodeFormat.QR_CODE, width, height, hints);
            int[] pixels = new int[width * height];
            for (int y = 0; y < height; y++) {
                for (int x = 0; x < width; x++) {
                    if (bitMatrix.get(x, y)) {
                        pixels[y * width + x] = 0xff000000;
                    } else {
                        pixels[y * width + x] = 0xffffffff;
                    }
                }
            }
            Bitmap bitmap = Bitmap.createBitmap(width, height,
                    Bitmap.Config.ARGB_8888);
            bitmap.setPixels(pixels, 0, width, 0, 0, width, height);
            return bitmap;
        } catch (WriterException e) {
            e.printStackTrace();
        }
        return null;
    }
}
